/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package radio_GUI;

import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import model.Artist;
import model.DBManager;
import model.Musicgroup;
import model.ArtistMusicgroup;

/**
 *
 * @author user
 */
public class EditMusicGroupForm extends javax.swing.JFrame {

 
    private EntityManager em;
    private model.Musicgroup m;//Αναφερετε η gui μεταβλητη musicgroup1
    private int flag = 0;//Ειδος φορμας
    //private Artist a = new Artist();
    
    private DefaultTableModel modelAr = new DefaultTableModel();
    private List<Artist> artInMG = new ArrayList<Artist>();    
    private boolean stayToThis = false;
    /**
     * Creates new form EditMusicGroupForm
     */
    public EditMusicGroupForm() {
        m = new model.Musicgroup();
        this.em = DBManager.getEm();
        initComponents();
        
    }
    
  
    public EditMusicGroupForm(Musicgroup m,int type) {
        this.em = DBManager.getEm(); 
        this.m = m;
        this.flag = type;
        
        initComponents();
        modelAr = (DefaultTableModel) jTableArt.getModel();
        if (flag == 1){//Διαγραφή form
            jLabel1.setText("Διαγραφή Μουσικού Συγκροτήματος");
            jButtonSave.setText("Διαγραφή");
        }else if (flag == 2){//Μεταβολή form
            jLabel1.setText("Μεταβολή Μουσικού Συγκροτήματος");
        }
        this.gemiseArtists();
        
    }
    public void gemiseArtists(){
        /*
        "Γεμιζουμε" την λίστα των καλλιτεχνων που ανίκουν στο συγκρότημα.
        Εκτελουμε query που γεμιζει βοηθητικό πίνκα artInMG και 
        το model του πίνακα.
        */
        modelAr = (DefaultTableModel) jTableArt.getModel();
        
        artInMG.clear();
        modelAr.setRowCount(0);
        Query q = em.createQuery("SELECT DISTINCT(a) FROM Artist a , ArtistMusicgroup b, "
      + "Musicgroup c WHERE b.musicgroupId = :mg1 AND b.artistId =a");
        q.setParameter("mg1", this.m);
        artInMG = (List<Artist>)  q.getResultList();    
        for (Artist ar: artInMG){
            Object[] rowData = {ar.getFirstname(),ar.getLastname(),
                                ar.getArtisticname()};
            modelAr.addRow(rowData);
            System.out.println(ar.getArtisticname());
        }
        jTableArt.setModel(modelAr);
    }
     
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        musicgroup1 = m;
        queryArtistsAll = java.beans.Beans.isDesignTime() ? null : DBManager.getEm().createQuery("SELECT a FROM Artist a");
        listArtistsAll = java.beans.Beans.isDesignTime() ? java.util.Collections.emptyList() : org.jdesktop.observablecollections.ObservableCollections.observableList(queryArtistsAll.getResultList());
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jButtonCancel = new javax.swing.JButton();
        jButtonSave = new javax.swing.JButton();
        jTextField2 = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTableArt = new javax.swing.JTable();
        jButtonInsert = new javax.swing.JButton();
        jButtonRemove = new javax.swing.JButton();
        DatePicker1 = new org.jdesktop.swingx.JXDatePicker();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTable2 = new javax.swing.JTable();
        jLabel5 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 12)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Εισαγωγή Συγκροτήματος");
        jLabel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        jLabel2.setText("Επωνυμία Συγκροτήματος");
        jLabel2.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel3.setText("Ημερομηνία Δημιουργίας");
        jLabel3.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jLabel4.setText("Λίστα Καλλιτεχνών");
        jLabel4.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        jButtonCancel.setText("Ακύρωση");
        jButtonCancel.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jButtonCancel.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonCancelActionPerformed(evt);
            }
        });

        jButtonSave.setText("Αποθήκευση");
        jButtonSave.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jButtonSave.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSaveActionPerformed(evt);
            }
        });

        org.jdesktop.beansbinding.Binding binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, musicgroup1, org.jdesktop.beansbinding.ELProperty.create("${name}"), jTextField2, org.jdesktop.beansbinding.BeanProperty.create("text"));
        bindingGroup.addBinding(binding);

        jTableArt.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Ονομα", "Επιθετο", "Καλλιτεχνικο ονομα"
            }
        ) {
            Class[] types = new Class [] {
                java.lang.String.class, java.lang.String.class, java.lang.String.class
            };
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public Class getColumnClass(int columnIndex) {
                return types [columnIndex];
            }

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jScrollPane1.setViewportView(jTableArt);

        jButtonInsert.setText("Εισαγωγή");
        jButtonInsert.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonInsertActionPerformed(evt);
            }
        });

        jButtonRemove.setText("Διαγραφή");
        jButtonRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonRemoveActionPerformed(evt);
            }
        });

        binding = org.jdesktop.beansbinding.Bindings.createAutoBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, musicgroup1, org.jdesktop.beansbinding.ELProperty.create("${formationdate}"), DatePicker1, org.jdesktop.beansbinding.BeanProperty.create("date"));
        bindingGroup.addBinding(binding);

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, listArtistsAll, jTable2);
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${firstname}"));
        columnBinding.setColumnName("Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${lastname}"));
        columnBinding.setColumnName("Επίθετο");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${artisticname}"));
        columnBinding.setColumnName("Καλλιτεχνικό Όνομα");
        columnBinding.setColumnClass(String.class);
        columnBinding.setEditable(false);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();
        jScrollPane2.setViewportView(jTable2);

        jLabel5.setText("Διαθέσιμοι Καλλιτέχνες");
        jLabel5.setBorder(javax.swing.BorderFactory.createBevelBorder(javax.swing.border.BevelBorder.RAISED));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                                .addComponent(jLabel3, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel2, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                .addGroup(layout.createSequentialGroup()
                                    .addGap(40, 40, 40)
                                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addComponent(DatePicker1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE))
                                    .addGap(366, 366, 366))
                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(jLabel5)
                                    .addGap(65, 65, 65))))
                        .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 397, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButtonInsert, javax.swing.GroupLayout.DEFAULT_SIZE, 105, Short.MAX_VALUE)
                            .addComponent(jButtonRemove, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jButtonSave, javax.swing.GroupLayout.PREFERRED_SIZE, 124, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addGap(18, 18, 18)
                                .addComponent(jButtonCancel, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 256, javax.swing.GroupLayout.PREFERRED_SIZE))))
                .addContainerGap(28, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(24, 24, 24)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(DatePicker1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jLabel4)
                    .addComponent(jLabel5))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(27, 27, 27)
                        .addComponent(jButtonInsert)
                        .addGap(18, 18, 18)
                        .addComponent(jButtonRemove))
                    .addGroup(layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 247, Short.MAX_VALUE)
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 129, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonCancel)
                    .addComponent(jButtonSave))
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButtonInsertActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonInsertActionPerformed
        /*Εισαγουμε Artist στο musicgroup
           Παιρνουμε την επιλεγμενη γραμμη(artist), 
        ,προσθετουμε την αντιστοιχη εγγραφη στον ενδιαμεσο 
        πινακα ArtistMusicgroup με persist
        */
        int row = jTable2.convertRowIndexToModel(jTable2.getSelectedRow());
        if (row>=0){
            Artist ar = listArtistsAll.get(row);
            if(!artInMG.contains(ar)){
                ArtistMusicgroup amg = new ArtistMusicgroup();
                amg.setMusicgroupId(this.m);
                amg.setArtistId(ar);
 
                em.getTransaction().begin();
                if(flag == 0){
                    em.persist(this.m);
                }
                em.persist(amg);
                em.getTransaction().commit();
                gemiseArtists();
            }else { 
                JOptionPane.showMessageDialog(this,
                    "Ο καλλιτέχνης υπάρχει ήδη στο group.");//Εμφάνιση μηνύματος
            }
        }else { 
            JOptionPane.showMessageDialog(this,
               "Παρακαλώ επιλέξτε γραμμή απο τον πίνακα.");//Εμφάνιση μηνύματος
        }
    }//GEN-LAST:event_jButtonInsertActionPerformed

    private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonCancelActionPerformed
        // Κουμπι Ακυρο
        this.dispose();//klisimo edit MusicGroup Form
        new MusicGroup().setVisible(true);
    }//GEN-LAST:event_jButtonCancelActionPerformed

    private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSaveActionPerformed
        // Αποθηκευση ή διαγραφή
        
        if(flag == 0){//Νεο music group
            if (artInMG.size() >= 2){
                em.getTransaction().begin();           
                em.persist(musicgroup1);
                em.getTransaction().commit();
                stayToThis = false;
            }else{
                stayToThis = true;
                JOptionPane.showMessageDialog(this,"Το group πρεπει να περιεχει"
                        + " τουλάχιστον 2 μέλυ.");//Εμφάνιση μηνύματος
            }
        } else if (flag == 2){//Μεταβολή music group
            
            if (artInMG.size() >= 2){
                em.getTransaction().begin();           
                em.merge(musicgroup1);
                em.flush();
                em.getTransaction().commit();
                stayToThis = false;
            }else{
                stayToThis = true;
                JOptionPane.showMessageDialog(this,"Το group πρεπει να περιεχει"
                        + " τουλάχιστον 2 μέλυ.");//Εμφάνιση μηνύματος
            }
        } else if (flag == 1){//Διαγραφή music group
        
            for (Artist ar: artInMG){    
                Query q = em.createQuery("SELECT b FROM ArtistMusicgroup b "
                        + " WHERE b.musicgroupId = :mg1 AND b.artistId = :ar");
                q.setParameter("mg1", this.musicgroup1);
                q.setParameter("ar", ar);
                ArtistMusicgroup amg =(ArtistMusicgroup) q.getSingleResult();
                em.getTransaction().begin();           
                em.remove(amg);
                em.getTransaction().commit();
            }
            em.getTransaction().begin();           
            em.remove(musicgroup1);
            em.getTransaction().commit();
            stayToThis = false;
        }
        if(!stayToThis){//Να παραμείνουμε στη Form
            this.dispose();
            new MusicGroup().setVisible(true);
        }
    }//GEN-LAST:event_jButtonSaveActionPerformed

    private void jButtonRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonRemoveActionPerformed
        /* Διαγραφή artist απο την λιστα του Music Group 
           πέρνουμε τον επιλεγμένο Artist, 
           βρισκουμε την εγγραφη ArtistMusicgroup ππου του αντιστοιχει,
           και την διαγράφουμε με τον em
        */
        
        int row = jTableArt.convertRowIndexToModel(jTableArt.getSelectedRow());
        if (row>=0){
            Artist ar = artInMG.get(row);
            Query q = em.createQuery("SELECT b FROM ArtistMusicgroup b "
                        + " WHERE b.musicgroupId = :mg1 AND b.artistId = :ar");
            q.setParameter("mg1", this.m);
            q.setParameter("ar", ar);
            ArtistMusicgroup amg =(ArtistMusicgroup) q.getSingleResult();
            em.getTransaction().begin();           
            em.remove(amg);
            em.getTransaction().commit();
            gemiseArtists();
        }else { 
            JOptionPane.showMessageDialog(this,
               "Παρακαλώ επιλέξτε γραμμή απο τον πίνακα.");//Εμφάνιση μηνύματος
        }
    }//GEN-LAST:event_jButtonRemoveActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(EditMusicGroupForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(EditMusicGroupForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(EditMusicGroupForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(EditMusicGroupForm.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                DBManager.openConnection();//Ksekina ton entity manager gia test                
                new EditMusicGroupForm().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private org.jdesktop.swingx.JXDatePicker DatePicker1;
    private javax.swing.JButton jButtonCancel;
    private javax.swing.JButton jButtonInsert;
    private javax.swing.JButton jButtonRemove;
    private javax.swing.JButton jButtonSave;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTable2;
    private javax.swing.JTable jTableArt;
    private javax.swing.JTextField jTextField2;
    private java.util.List<Artist> listArtistsAll;
    private model.Musicgroup musicgroup1;
    private javax.persistence.Query queryArtistsAll;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables

    
   
    
}

